<?php
declare (strict_types = 1);

namespace app\h5\controller;
use think\facade\Session;
use think\facade\Config;
use think\facade\Db;
use app\wx_pay\controller\JsApiPayV2;
class Index
{

    /**
     * 在前端加载调用，判断session是否存在
    */
    public function getUserStatus(){
        if(empty(Session::get('openid'))){
            return json(array("status"=>500,"msg"=>"用户session状态已失效，请调用权限获取"));
        }else{
            return json(array("status"=>200,"msg"=>"ok"));
        }
    }
    /**
     * 回调到此方法
     * snsapi_base仅获取openid
     * snsapi_userinfo 获取用户的基本信息
     */
    public function getUserInfo(){
        $code = $_GET['code'];//接收回调的code
        //通过code换取网页授权access_token
        $access_token_url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".Config('wx')['accountAppId']."&secret=".Config('wx')['accountAppSecret']."&code=".$code."&grant_type=authorization_code";
        $access_token_data = json_decode( req_Get($access_token_url),true);
        $access_token = $access_token_data['access_token'];
        $openid = $access_token_data['openid'];
        Session::set('openid',$openid);
        //查询用户是否存入数据库
        $select_wx_user = Db::table('wx_user')->where('wx_openid',$openid)->find();
		/**
		 * 前端为snsapi_userinfo才可执行，否则报错
		 * 获取用户信息
		 */
		$user_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
		$user = json_decode( req_Get($user_url),true);
		$result = [];
		$result['wx_openid'] = $user['openid'];
		$result['wx_nickname'] = $user['nickname'];
		$result['wx_sex'] = $user['sex'];
		$result['wx_city'] = $user['city'];
		$result['wx_province'] = $user['province'];
		$result['wx_headimgurl'] = $user['headimgurl'];
		$result['wx_create_time'] = date("Y-m-d H:i:s");
        if(empty($select_wx_user)){
            /**
             * DROP TABLE IF EXISTS `wx_user`;

            CREATE TABLE `wx_user` (
            `wx_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '微信用户id',
            `wx_openid` varchar(50) DEFAULT NULL COMMENT '微信用户唯一标识',
            `wx_nickname` varchar(255) DEFAULT NULL COMMENT '微信用户昵称',
            `wx_sex` mediumint(1) DEFAULT NULL COMMENT '微信用户性别',
            `wx_city` text COMMENT '微信用户地区',
            `wx_province` text COMMENT '微信用户省',
            `wx_headimgurl` text COMMENT '微信用户头像',
            `wx_create_time` datetime DEFAULT NULL,
            PRIMARY KEY (`wx_id`),
            UNIQUE KEY `wx_openid` (`wx_openid`),
            KEY `wx_id` (`wx_id`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;

             */

            Db::table('wx_user')->insert($result);
        }else{
			Db::table('wx_user')->where('wx_openid',$openid)->update($result);
		}
        return redirect($_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']);
    }
    /**
     * 回调到此方法
     * snsapi_base仅获取openid
     * snsapi_userinfo 获取用户的基本信息
     */
    public function commonGetUserInfo(){
        $wx_openid = $_REQUEST['openid'];
        $wx_nickname = $_REQUEST['nickname'];
        $wx_headimgurl = $_REQUEST['headImgUrl'];
        Session::set('openid',$wx_openid);
        //查询用户是否存入数据库
        $select_wx_user = Db::table('wx_user')->where('wx_openid',$wx_openid)->find();
		$result = [];
		$result['wx_openid'] = $wx_openid;
		$result['wx_nickname'] = $wx_nickname;
		$result['wx_sex'] = '';
		$result['wx_city'] = '';
		$result['wx_province'] = '';
		$result['wx_headimgurl'] = $wx_headimgurl;
		$result['wx_create_time'] = date("Y-m-d H:i:s");
        if(empty($select_wx_user)){
            Db::table('wx_user')->insert($result);
        }else{
			Db::table('wx_user')->where('wx_openid',$wx_openid)->update($result);
		}
        $url =  $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
        return redirect($url);
    }	
    /**
     *执行支付
     * $add_id 用户id
     * $pay_price 支付金额
    */
    public function webPay($add_id,$pay_price){
        /**
         * DROP TABLE IF EXISTS `sign_order`;

        CREATE TABLE `sign_order` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `out_trade_no` varchar(32) DEFAULT NULL COMMENT '订单号',
        `uid` int(11) DEFAULT '0' COMMENT '用户id',
        `ispay` tinyint(4) DEFAULT '0' COMMENT '是否支付成功',
        `pay_time` datetime DEFAULT NULL COMMENT '支付时间',
        `pay_price` decimal(10,2) DEFAULT NULL,
        `add_time` datetime DEFAULT NULL,
        `num` varchar(100) DEFAULT NULL COMMENT '报名人数',
        `danwei` varchar(100) DEFAULT NULL COMMENT '单位',
        `emailaddress` varchar(255) DEFAULT NULL COMMENT '邮寄地址',
        `shibiehao` varchar(255) DEFAULT NULL COMMENT '纳税人识别号',
        `fapiao` varchar(50) DEFAULT NULL COMMENT '发票领取方式',
        `beizhu` text COMMENT '备注',
        `xinxiang` varchar(255) DEFAULT NULL COMMENT '收票信箱',
        PRIMARY KEY (`id`),
        UNIQUE KEY `out_trade_no` (`out_trade_no`),
        KEY `u_id` (`uid`) USING BTREE
        ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;

         *
        */
        $appid = Config('wx')['accountAppId'];
        $result = [];
        $result['add_time'] = date('Y-m-d H:i:s');
        $result["out_trade_no"] = genAppNo();//订单号
        $result['uid'] =$add_id;
        $result['pay_price'] = $pay_price;
        $res = Db::table('sign_order')->insert($result);
        if ($res) {
            $backurl = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']."/wx_pay/js_api_pay/paySuccess";
            //https://plqlrzqynb.wdkj.vip/test/public/index.php/wx_applet/Wx/paysuccess支付成功回调地址
            $wx = new JsApiPayV2();
            $pay_info = $wx->wx_pay($appid,$result["out_trade_no"],Session::get('openid'), $result['pay_price'], $backurl);
            $pay_info['money'] = $result['pay_price'];
            return array('status' => 200, 'msg' => 'ok', "data" => $pay_info);
        } else {
            return array('status' => 500, 'msg' => '发生错误');
        }
    }
    public function webRefund($out_trade_no,$money){
        $wx = new JsApiPayV2();
        $appid = config('wx')['accountAppId'];
        $wx->refund($appid,$out_trade_no, $money);
    }
    /**
     *分享生成卡片
     * $titles 标题
     * $desc 分享描述
     * $imgUrl 分享图标
     */
    public function share($titles,$desc,$imgUrl){
        $time = time();
        $expires_in_time = Db::table("access_token")->where("access_id",1)->value("time");
        $access_token_value = Db::table("access_token")->where("access_id",1)->value("access_token_value");
        if($time > $expires_in_time){
            $this->getAccessToken();
            $access_token_value = Db::table("access_token")->where("access_id",1)->value("access_token_value");
        }
        $curl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token_value."&type=jsapi";
        $jsapi_ticket =json_decode(req_Get($curl),true);

        $ticket =$jsapi_ticket['ticket'];
//        var_dump($ticket);
        $url = $_SERVER['HTTP_REFERER'];
        $nonceStr = rand_code();
        //$config = "jsapi_ticket=".$ticket."&noncestr=".$this->rand_code()."&timestamp=".$time."&url=".$url;
        $config = "jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$time}&url={$url}";
        $result = [
            'appId'=>config('wx')['accountAppId'],// 必填，公众号的唯一标识
            'timestamp'=>$time,// 必填，生成签名的时间戳
            'nonceStr'=>$nonceStr,// 必填，生成签名的随机串
            'signature'=>sha1($config),//$this->signature($config) 必填，签名
            'jsapi_ticket'=>$ticket,
            'string1'=>$config,
            'title'=>$titles,//"珠海市飓风足球俱乐部报名系统",
            'desc'=>$desc,//'珠海市飓风足球俱乐部，欢迎您的加入！',// 分享描述
            'link'=>$url,// 分享链接，该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
            'imgUrl'=>$imgUrl //'http://blqzqbm.yyuebd.com/storage/uploads/20220816/899d397d48eb2e96c1a3e190bef8b858.png'//分享图标
        ];
        return ['status'=>200,'data'=>$result];
    }
    protected function getAccessToken(){
        /**
         *
         CREATE TABLE `access_token` (
        `access_id` int(11) NOT NULL AUTO_INCREMENT ,
        `access_token_value` text NOT NULL,
        `time` bigint(20) NOT NULL,
        PRIMARY KEY (`access_id`),
        KEY `wx_id` (`access_id`)
        ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
		
		INSERT INTO `access_token` (`access_id`, `access_token_value`, `time`) VALUES ('1', 'sadsad', '451511');
		
        **/
        $access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".config('wx')['accountAppId']."&secret=".config('wx')['accountAppSecret'];
        $access =json_decode(req_Get($access_token_url),true);
        $access_token = $access['access_token'];
        Db::table("access_token")->where("access_id",1)->update([
            "access_token_value"=>$access_token,
            "time"=>time()+7200
        ]);
    }
    /**
     * 发送订阅消息---关注公众号才可接收到
     * $udata根据模板来自定义
     * $template_id 模板id
     * 其他字段自定义
    */
    public function sendApi($openid,$template_id,$header,$time,$phone,$nickName,$remark){
        $access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".config('wx')['accountAppId']."&secret=".config('wx')['accountAppSecret'];
        $access_token_data = json_decode(req_Get($access_token_url),true);
        $access_token = $access_token_data['access_token'];
        // var_dump($ACCESS_TOKEN);die;
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
        ///根据模板自定义内容和字段///
        $udata['touser'] = $openid;//接收者openid
        $udata['template_id'] = $template_id;//Rrxm6HU6idUNFdoyyamx_a5MB1SiWslYs4AdYKKc22s模板ID
        $udata['data']['first']['value'] = $header;
        $udata['data']['keyword1']['value']  =(string)$time;
        $udata['data']['keyword2']['value']  =$phone;
        $udata['data']['keyword3']['value']  =$nickName;
        $udata['data']['remark']['value']  = $remark;
        $res = req_Post($url,json_encode($udata));
        return $res;
    }
}
